<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  <title>Document</title>
  <!-- 导入页面的基本样式 -->
  <link rel="stylesheet" href="./css/search.css" />
  <!-- 导入 jQuery -->
  <script src="./lib/jquery.js"></script>
  <script src="./lib/template-web.js"></script>
</head>
<style>
  /* .sug:nth-child(2n) {
    background-color: #ccc;
  }
  .sug:nth-child(2n+1) {
    background-color: rgb(153, 148, 148);
  } */
  #suggest-list {
    border: 1px solid #000;
    border-top: none;
    display: none;
  }

  .sug:hover {
    background-color: hotpink;
  }

  .sug {
    line-height: 30px;
    padding-left: 5px;
    font-size: 16px;
  }
</style>

<body>
  <div class="container">
    <!-- Logo -->
    <img src="./images/taobao_logo.png" alt="" class="logo" />

    <div class="box">
      <!-- tab 栏 -->
      <div class="tabs">
        <div class="tab-active">宝贝</div>
        <div>店铺</div>
      </div>
      <!-- 搜索区域（搜索框和搜索按钮） -->
      <div class="search-box">
        <input id="inp" type="text" class="ipt" placeholder="请输入要搜索的内容" /><button class="btnSearch">
          搜索
        </button>
      </div>
      <div id="suggest-list">

      </div>
    </div>
  </div>
  <script type="text/html" id="mb">
    {{each result}}
      <div class="sug">{{$value[0]}}</div>
    {{/each}}
  </script>
</body>
<script>
  $(function () {
    let timer = null
    var obj = {}
    // 定义防抖函数
    function fdFn(key) {
      timer = setTimeout(function () {
        getRes(key);
      }, 500)
    }

    $('#inp').on('keyup', function () {
      clearTimeout(timer)
      let val = $(this).val().trim()
      if (val <= 0) {
        $('#suggest-list').empty().hide()
        return
      }
      // console.log(val.trim());
      $('#suggest-list').show()

      if (obj[val]) {
        return console.log(obj[val])
      }
      fdFn(val)
    })

    function getRes(fw) {
      $.ajax({
        type: 'GET',
        url: 'https://suggest.taobao.com/sug?q=' + fw,
        dataType: 'jsonp',
        success: res => {
          console.log(res.result)
          let html = template('mb', res)
          $('#suggest-list').html(html)
          obj[$('#inp').val()] = res
        }
      })
    }


    $('#suggest-list').on('click', '.sug', function () {
      $('#inp').val($(this).html())
      $('#suggest-list').empty().hide()

    })
  })
</script>

</html>